<template>
  <div>
    <div v-if="token != null" class="nav-main">
      <div class="nav">
        <van-nav-bar
          :title="this.$route.query.id ? '修改订单信息' : '添加订单'"
          left-arrow
          @click-right="onClickRight"
          @click-left="onClickLeft"
        >
          <van-icon name="share" slot="right" />
        </van-nav-bar>
      </div>
    </div>
    <div v-else-if="token == null" class="nav-main">
      <van-nav-bar title="添加订单" class="nav"></van-nav-bar>
    </div>
   
    <div class="sale_list">
      <!-- <h4>普通批发</h4> -->
      <ul>
        <!-- <li v-for="(item,index) in info" :key="index">
                
                <div class="sale_left">
               <img :src="item.img" alt="">
               </div>
           <div class="bottom">
              <div class="bottom_name">
                        <h2>{{item.name}}</h2>
              </div> 
              <div class="new_bottom">
                    <div v-if="token!=null" class="bottom_left">
                        <p>￥{{item.price}}</p>
                        <small>拿货价 ￥{{item.price2}}</small>
                    </div>

                    <div v-else-if="token==null">
                        <p>￥{{item.price}}</p>
                    </div>
                
                    <div class="sale_rigth">
                        <van-stepper v-model="item.num" :min="0" :default-value="0"/>
                    </div> 
              </div>
            </div>  
            </li> -->
        <li v-for="item in info">
          <div class="sale_left">
            <img :src="item.img" alt="" />
            <div v-if="token != null">
              <h2>{{ item.name }}</h2>
              <p>￥{{ item.price }}</p>
              <small>拿货价 ￥{{ item.price2 }}</small>
            </div>
            <div v-else="token == null">
              <h2>{{ item.name }}</h2>
              <p>￥{{ item.price }}</p>
            </div>
          </div>

          <div class="sale_rigth">
            <van-stepper v-model="item.num" :min="0" :default-value="0" />
          </div>
        </li>
      </ul>
    </div>
    <footer>
      <h5>总计：{{ all }}包</h5>
      <p>￥{{ product }}</p>
      <p>
        <strong @click="Porder"> 确定 </strong>
      </p>
    </footer>
    <div class="popup" v-show="isShow">
      <!-- <span>{{url}}{{id}}<img src="../../assets/i//01/关闭.png" alt="" @click="close"></span> -->
      <!-- <textarea  id="biao1">{{url}}{{phone}}</textarea> -->
      <textarea id="biao1">{{ url }}{{ id }}</textarea>
      <div ref="qrCodeUrl"></div>
      <div class="btm">
        <button
          type="text"
          v-clipboard:copy="sysAppIds"
          v-clipboard:success="onCopy"
          v-clipboard:error="onError"
        >
          复制分享链接
        </button>
        <button @click="close">下次再说</button>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import QRCode from "qrcodejs2";
import { NavBar, Icon, Stepper, Toast } from "vant";
Vue.use(NavBar).use(Icon).use(Stepper);
export default {
  data() {
    return {
      //   sysAppIds:'瑶妹美食客户下单链接：'+'http://51yaomei.com/share/#/shop/'+localStorage.getItem("username"),
      sysAppIds:
        "瑶妹美食客户下单链接：" +
        "http://yaomei.weilang.top/share/#/shop/" +
        localStorage.getItem("id"),
      // sysAppIds:
      //   "瑶妹美食客户下单链接：" +
      //   "http://51yaomei.com/share/#/shop/" +
      //   localStorage.getItem("id"),
      info: [],
      isShow: false,
      url: "瑶妹美食客户下单链接：" + "http://yaomei.weilang.top/share/#/shop/",
      // url: "瑶妹美食客户下单链接：" + "http://51yaomei.com/share/#/shop/",
      id: this.$route.params.id,
      phone: localStorage.getItem("username"),
      token: localStorage.getItem("token"),
      request_info: {},
    };
  },
  computed: {
    all() {
      var allNum = 0;
      var that = this;
      for (let i = 0; i < that.info.length; i++) {
        allNum += that.info[i].num;
      }
      return allNum;
    },
    product() {
      var all = 0;
      var _this = this;
      for (let i = 0; i < _this.info.length; i++) {
        all += _this.info[i].num * _this.info[i].price2;
      }
      return all;
    },
  },
  beforeRouteLeave(to, from, next) {
    localStorage.removeItem("goods_info");
    localStorage.removeItem("request_info");
    next();
  },
  methods: {
    creatQrCode() {
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: this.sysAppIds, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    },
    onClickRight() {
      this.isShow = true;
    },
    onClickLeft() {
      this.$router.back(-1);
    },
    async Porder() {
      //如果为总经销可修改分销的订单
      //分销自己的订单
      var listdata = [];
      var list = [];
      var _this = this;
      for (let i = 0; i < _this.info.length; i++) {
        if (_this.info[i].num != 0) {
          list = {
            id: _this.info[i].id,
            num: _this.info[i].num,
          };
          listdata.push(list);
        }
      }
      if (listdata.length > 0) {
        
        if (!localStorage.getItem("goods_info")) {
          localStorage.setItem("data", JSON.stringify(listdata));
          this.$router.push({
            path: "/order_detail",
            flag: 1,
          });
        } else {
            //这里是修改订单
          try {
            const res = await this.apiPost("order/fill_order", {
              token: localStorage.getItem("token"),
              // user_id:localStorage.getItem('id'),
            //   goods: localStorage.getItem("data"),
              goods: JSON.stringify(listdata),
              order_user_id: this.$route.params.id,
            });
            if (res.data.code == 200) {
              const goods = Object.assign(
                {},
                res.data.data,
                JSON.parse(localStorage.getItem("request_info"))
              );
              switch (goods.log_type) {
                case "普通快递":
                  goods.log_type = 1;
                  break;
                case "顺丰空运":
                  goods.log_type = 2;
                  break;
                case "顺丰陆运":
                  goods.log_type = 3;
                  break;
                case "无需运费":
                  goods.log_type = 4;
                  break;
              }
              // console.log("这里修改了快递",goods);

              const res1 = await this.apiPost("order/confirm_sub", {
                goods: JSON.stringify(goods),
              });
              let _goods = res1.data.data;
              _goods.postage -= 1;
              if (res1.data.code === 200) {
                // console.log(_goods);
                const res2 = await this.apiPost("order/sub_order", {
                  token: localStorage.getItem("token"),
                  goods: JSON.stringify(_goods),
                  old_order_no: this.$route.query.order_no,
                  order_user_id: this.$route.params.id,
                });
                if (res2.data.code === 200) {
                    localStorage.removeItem("goods_info")
                    localStorage.removeItem("goods_info")
                  this.$router.push(`/ord/${res2.data.data}`);
                } else {
                  Toast(res2.data.message);
                }
              } else {
                Toast(res1.data.message);
              }
            }
          } catch (error) {
            Toast("出现错误，请重新再试");
          }

          //发送确认订单的请求
        }
      } else {
        Toast("请选择完商品后再提交");
      }
    },
    close() {
      this.isShow = false;
    },
    // 复制成功
    onCopy(e) {
      // alert("已复制好，可贴粘。");
      this.isShow = false;

      // this.creatQrCode() 调用二维码
      Toast("已复制，去粘贴");
    },
    // 复制失败
    onError(e) {
      alert("失败");
    },
    getLocalData() {
      // console.log(this.info);
      let data = localStorage.getItem("data");
      let goods_info = localStorage.getItem("goods_info");
      // console.log(data);

      if (goods_info) {
        JSON.parse(goods_info).forEach((item) => {
          let goods = this.info.filter((v) => {
            return v.id == item.id;
          });
          goods.forEach((key) => {
            key.num = item.num;
          });
        });
      } else if (data) {
        JSON.parse(data).forEach((item) => {
          let goods = this.info.filter((v) => {
            return v.id == item.id;
          });
          goods.forEach((key) => {
            key.num = item.num;
          });
        });
      }
    },
  },
  mounted() {
    if (localStorage.getItem("token")) {
      this.apiGet("goods/goods_list", {
        token: localStorage.getItem("token"),
      }).then((res) => {
        var datalist = res.data;
        if (datalist.code == 200) {
          var values = datalist.data;
          var list = [];
          var items = [];
          values.forEach((item) => {
            list = {
              name: item.name,
              price: item.price,
              price2: item.price2,
              num: item.num,
              id: item.id,
              img: item.img,
            };
            items.push(list);
          });
          this.info = items;
          this.getLocalData();
        } else {
          Toast(datalist.message);
        }
      });
    } else {
      this.apiGet("goods/goods_list", {
        user_id: this.$route.params.id,
      }).then((res) => {
        localStorage.setItem("id", this.$route.params.id);
        var datalist = res.data;
        if (datalist.code == 200) {
          var values = datalist.data;
          var list = [];
          var items = [];
          values.forEach((item) => {
            list = {
              name: item.name,
              price: item.price,
              price2: item.price2,
              num: item.num,
              id: item.id,
              img: item.img,
            };
            items.push(list);
          });
          this.info = items;
          this.getLocalData();
        } else {
          Toast(datalist.message);
        }
      });
    }
  },
};
</script>

<style scoped>
.nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9998;
}
.sale_list {
  background-color: #fff;
  padding: 0 0.5em;
  margin: 3em 0 5em 0;
}
.sale_list h4 {
  font-size: 0.9em;
  text-align: left;
  margin: 0 0.5em;
  border-bottom: 1px solid #f4f4f4;
  padding: 0.3em 0;
}
.sale_list ul li {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border-bottom: 1px solid #f4f4f4;
  padding: 0.5em 0;
}

.sale_list ul li .sale_left {
  display: flex;
  flex-direction: row;
}
.sale_list ul li img {
  display: block;
  width: 6em;
  height: 6em;
  background-color: #ccc;
  margin: 0 0.5em;
}
.sale_list ul li h2 {
  font-weight: normal;
  font-size: 1em;
}
.sale_list ul li p {
  color: #b43e3a;
  font-size: 0.9em;
}
.sale_list ul li div {
  text-align: left;
}
.sale_list small {
  color: #ccc;
}
.sale_left div {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.sale_rigth {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

footer {
  position: fixed;
  width: 100%;
  line-height: 3em;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  bottom: 0;
  background-color: #fff;
  font-size: 1em;
  /* padding: 0 1em; */
}
footer p {
  color: #b43e3a;
  font-size: 0.9em;
}

footer strong {
  padding: 0.2em 1.5em;
  border: 1px solid #b43e3a;
  border-radius: 1em;
}
.popup {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.popup textarea {
  width: 80%;
  min-height: 50px;
  margin-top: 10em;
  display: inline-block;
  background-color: #fff;
  padding: 10px;
  white-space: normal;
  word-break: break-all;
  text-align: center;
  position: relative;
}
.popup button {
  width: 40%;
  padding: 10px 10px;
  background-color: forestgreen;
  color: white;
  outline: none;
  border: none;
}
.btm {
  display: flex;
  width: 80%;
  margin-left: 10%;
  justify-content: space-around;
}
.popup button:last-child {
  background-color: #b43e3a;
}
</style>
